package com.weimengchao.core.http;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class ResponseEntityUtils {

    /**
     * @description: 获取Excel文件流
     * @createAuthor: 魏孟超
     * @createDate: 2021/10/15 21:50
     * @params:
     * @return:
     */
    public static ResponseEntity getResponseEntityForExcel(byte[] bytes, String fileName) throws UnsupportedEncodingException {
        //返回Excel文件流
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(bytes.length)
                .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                .body(new InputStreamResource(new ByteArrayInputStream(bytes)));
    }

}
